
<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from "vue"
import {Search} from "@element-plus/icons-vue";
import productItemVue from "@/views/productItem.vue"
import {getGoodsService} from "@/api/goods.js";
import { useRouter} from 'vue-router'
import {getHotSearchService} from "@/api/HotSearch.js";
import {useTokenStore} from "@/stores/token.js";
import {getUserInfoService} from "@/api/user.js";
import {ElMessage} from "element-plus";
import {useUserIdStore} from "@/stores/userInfo.js";
import {useDefaultAvatarStore} from "@/stores/defaultAvatar.js";
import {getTotalNoticeNumService} from "@/api/messages.js";
import {saveUserBehaviorService} from "@/api/userBehavior.js";


const route = useRouter()
const title = ref('')

//搜索框关键字
const searchInput = ref("")

const showUserMessage = ref(false)


let currentPage = ref(1); //当前页数
const pageSize = ref(21); //每页显示条数
const total = ref(0); //总条数
const hasMore = ref(true); //是否还有更多数据
const totalNoticeNum = ref(0); // 当前用户总共未读消息数量 在首页展示

const tokenStore = useTokenStore()

// 用户行为
const userBehavior = reactive({
  behaviorType:null,
  searchKeyword:null
});

const getTotalNoticeNum = async () => {
  if (tokenStore.token === ''){
    return;
  }
  let result = await getTotalNoticeNumService();
  totalNoticeNum.value = result.data;
}
getTotalNoticeNum();

const intervalId2 = setInterval(async () => {
  await getTotalNoticeNum();
}, 10000);

onMounted(()=>{
  title.value = route.currentRoute.value.meta.title;
  document.title = title.value;

  let routeSearchInput = route.currentRoute.value.query.search;
  if (routeSearchInput !== undefined || true || routeSearchInput !== ''){
    searchInput.value = routeSearchInput;
  }
})

//默认商品信息列表
const goodsList = ref([])

const getGoodsList = async () => {
  let result = await getGoodsService(currentPage.value, pageSize.value)
  // 判断是否还有更多数据
  if (result.data.total <= currentPage.value * pageSize.value) {
    hasMore.value = false;
  }
  goodsList.value.push(...result.data.records);
  total.value = result.data.total
  currentPage.value += 1;
}

const resetData = () => {
  currentPage.value = 1;
  goodsList.value = [];
  hasMore.value = true;
}

const onProductItemShowDetails = (clickedGoods) => {
  // 在此处处理点击商品后的逻辑，例如记录当前查看商品ID等
  console.log('正在查看商品:', clickedGoods.id);
};
const onSearch = async () => {
  let result = await getGoodsService(currentPage.value, pageSize.value, searchInput.value);
  // 判断是否还有更多数据
  if (result.data.total <= currentPage.value * pageSize.value) {
    hasMore.value = false;
  }
  goodsList.value.push(...result.data.records);
  total.value = result.data.total
  currentPage.value += 1;
}

const keyupEvent = (event) => {
  if (event.key === "Enter") {
    event.preventDefault();
    event.stopPropagation();
    console.log('Enter键被按下');
    onSearch();
  }
}
window.addEventListener('keyup', keyupEvent)

onBeforeUnmount(() => {
  window.removeEventListener('keyup', keyupEvent);
  clearInterval(intervalId);
  clearInterval(intervalId2);
})

const getList = () => {
  if (searchInput.value === "") {
    getGoodsList()
  } else {
    onSearch()
  }
}
// 热搜
const HotSearchStatus = ref(false)
// 热搜展示数据
const hotSearchData = ref([])

const getHotSearchData = async () => {
  let result = await getHotSearchService();
  hotSearchData.value = result.data
}
const openHotSearch = () => {
  HotSearchStatus.value = true;
  getHotSearchData()
}

const closeHotSearch = () => {
  HotSearchStatus.value = false;
}

const buttonSearch = () => {
  resetData();
  userBehavior.behaviorType = 1;
  userBehavior.searchKeyword = searchInput.value;
  saveUserBehaviorService(userBehavior);
  route.replace({path:'/layout',query:{search:searchInput.value}});
}

const hotRowItemClicked = (item) => {
  searchInput.value = item
  HotSearchStatus.value = false;
}
const token = useTokenStore()

const goHomePage = () => {
  HotSearchStatus.value = false;
  route.push('/')
}

const userAvatar = ref('')
const defaultAvatarStore = useDefaultAvatarStore();
//默认头像
const defaultPic = ref(defaultAvatarStore.defaultAvatar)
const getUserAvatar = async () => {
  let result = await getUserInfoService();
  userAvatar.value = result.data.userPic === "" || result.data.userPic === null ? defaultPic.value : result.data.userPic;
}
getUserAvatar();

const showMessage = () => {
  showUserMessage.value = true;
}


const closeMessage = () => {
  showUserMessage.value = false;
}

const flag = ref(false) //控制消息中心字体闪烁
const intervalId =setInterval(()=>{
  flag.value = !flag.value;
},300)

const userIdStore = useUserIdStore();
//退出登录
const logout = () => {
  token.removeToken();
  userIdStore.removeUserId();
  showUserMessage.value = false;
  location.reload(); //刷新页面
  ElMessage.success('退出成功')
}
</script>

<template>
  <el-container class="layout-container">
    <el-header class="layout-header" @click.self="closeHotSearch">
      <!--  <p>校林二手交易圈</p>-->
      <img class="logo" src="../assets/logo1.png" alt="logo" @click="goHomePage"/>
      <div class="left-title-nav">
        <el-link href="/">首页</el-link>
        <el-link href="/">分类</el-link>
      </div>
      <div class="search-input">
        <el-input class="search"
                  v-model="searchInput"
                  placeholder="搜索一下"
                  @focus="openHotSearch"
                  :prefix-icon="Search"/>
        <el-button type="primary" class="search-button" @click="buttonSearch" @focus="closeHotSearch">搜索</el-button>
        <div class="title-nav">
          <el-link href="/layout">所有商品</el-link>
          <el-link href="/requiredGoods">求购广场</el-link>
          <el-link href="/AITalk">校林AI助手</el-link>
        </div>
      </div>
      <div v-show="HotSearchStatus" class="hot-search">
        <p>热门搜索</p>
        <el-row
            v-for="item in hotSearchData"
            :key="item"
            class="hot-row"
            @click="hotRowItemClicked(item)">
          <span>{{ item }}</span>
        </el-row>
      </div>
      <div class="login-div">
        <el-link v-if="token.token === null || token.token.length === 0" class="login" href="/login"><p>登录</p>
        </el-link>
        <div v-else class="avatar-info" @mouseover="showMessage" @mouseleave="closeMessage">
          <div style="height: 100%;display: flex;align-items: center;position: relative">
            <img :src="userAvatar" alt="avatar" style="border-radius: 50%;background-size: cover;width: 40px;height: 40px;">
            <p v-if="totalNoticeNum!==0" class="total-notice">{{totalNoticeNum}}</p>
          </div>
          <div v-if="showUserMessage" class="user-message" @mouseleave="closeMessage">
            <div class="user-message-item"  @click="route.push('/pushRequiredGoods')"><p style="font-weight: bold">发布求购</p></div>
            <div class="user-message-item" @click="route.push('/pushGoods')"><p style="font-weight: bold">发布商品</p>
            </div>
            <div class="user-message-item" @click="route.push('/myPushCenter')"><p style="font-weight: bold">我的发布</p></div>
            <div class="user-message-item" @click="route.push('/messageCenter')">
              <p style="font-weight: bold;" :style="totalNoticeNum!==0&&flag ? {color: 'red'} : {}">消息中心</p>
            </div>
            <div class="user-message-item" @click="route.push('/personalCenter')"><p style="font-weight: bold">
              个人中心</p></div>
            <div class="user-message-item" @click="logout"><p style="font-weight: bold">退出登录</p></div>
          </div>
        </div>
      </div>
    </el-header>
    <el-main
        class="layout-main"
        @click="closeHotSearch"
        v-infinite-scroll="getList"
        :infinite-scroll-disabled="!hasMore"
        :infinite-scroll-distance="10"
        :infinite-scroll-immediate-check="false"
        @infinite-scroll-complete=""
        :infinite-scroll-delay="1000">
      <el-container
          class="grid-container"
      >
        <product-item-vue
            class="product-item"
            v-for="item in goodsList"
            :key="item.id"
            :goods="item"
            :on-show-details="onProductItemShowDetails"
        >
        </product-item-vue>
      </el-container>
      <div v-if="hasMore" v-loading="true" element-loading-text="加载中..." class="data-loading"></div>
      <p v-if="!hasMore">没有更多了...</p>
    </el-main>
  </el-container>
</template>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;
  width: 100%;

  .layout-header {
    background-color: #e8e8e8;
    height: 55px;
    display: flex;
    flex-direction: row;
    align-items: center;
    position: relative;
    transition: all 0.3s ease-in-out;

    img {
      height: 70%;

      &:hover {
        cursor: pointer;
      }
    }

    .search-input {
      height: 100%;
      width: auto;
      display: flex;
      position: absolute;
      left: 35%;
      top: 15%;
    }

    .search {
      height: 70%;
      width: 350px;
      border-radius: 1px;
    }

    .hot-search {
      position: absolute;
      left: 35%;
      top: 85%;
      z-index: 1000;
      width: 349px;
      min-height: 50px;
      background-color: #fdfdfd;
      box-shadow: 0 5px 10px rgba(0, 0, 0, 0.4);
      border-radius: 0 0 10px 10px;

      p {
        margin: 10px;
        font-size: 15px;
        font-weight: bold;
        color: #000000;
      }

      .hot-row {
        width: 100%;
        height: auto;

        span {
          width: 100%;
          padding: 5px 0;
          margin-left: 10px;
          font-size: 15px;
          color: #545454;
          white-space: nowrap;
          overflow:hidden;
          text-overflow: ellipsis;
        }

        &:hover {
          background-color: #d2d0d0;
          cursor: pointer;
        }
      }
    }

    .search-button {
      //margin-left: 20px;
      //position: absolute;
      //right: 38%;
      margin-left: 10px;
      margin-top: 1px;
      height: 65%;
      width: 90px;
      background-color: #f66002;
      border: 1px solid #f66002;

      &:hover {
        background-color: rgb(255, 0, 0);
      }
    }

    .login-div {
      height: 100%;
      width: 70px;
      position: absolute;
      right: 25px;
      display: flex;
      align-items: center;

      img {
        height: 60%;
        width: 60%;
      }
    }

    .login {
      height: 100%;
      width: 100%;
      font-size: 18px;
      text-decoration: none;

      p {
        font-weight: bold;
      }

      &:hover {
        cursor: pointer;
        background-color: white;
        border-radius: 3px;
        color: #f66002;
        transition: all 0.3s ease-in-out;
      }
    }

    .left-title-nav {
      width: 160px;
      height: 100%;

      .el-link {
        width: 80px;
      }
    }

    .title-nav {
      height: 100%;
      margin-left: 60px;
      margin-top: -9px;
      display: flex;
      justify-content: space-between;
    }

    .el-link {
      height: 100%;
      width: 100px;
      font-size: 15px;
      text-decoration: none;
      &:hover {
        cursor: pointer;
        background-color: white;
        border-radius: 3px;
        color: #f66002;
        transition: all 0.3s ease-in-out;
      }
    }
  }

  .avatar-info {
    .total-notice{
      position: absolute;
      color: #fff;
      margin: 0;
      background-color: #ff0000;
      border-radius: 50%;
      width: 19px;
      height: 19px;
      text-align: center;
      line-height: 19px;
      font-size: 10px;
      top: -5px;
      right: -5px;
    }
  }

  .user-message {
    width: 100px;
    height: auto;
    background-color: white;
    border-radius: 10px;
    position: absolute;
    right: 0;
    top: 48px;

    .user-message-item {
      width: 100%;
      height: 20px;
      text-align: center;
      padding: 5px 0;
      cursor: pointer;

      p {
        font-size: 15px;
        font-weight: bold;
        margin: 0;
      }

      &:hover {
        background-color: #f66002;
        border-radius: 10px;
        color: white;
      }
    }
  }

  .layout-main {
    width: 100%;
    .grid-container {
      width: 76%;
      display: grid;
      grid-template-columns: repeat(4, 1fr); // 创建四列布局
      margin: 0 auto;

      .product-item {
        margin-bottom: 15px;
      }
    }

    .data-loading {
      margin-top: 10px;
      text-align: center;
    }

    p {
      border-top: 1px solid #999;
      text-align: center;
      color: #999;
      font-size: 20px;
      padding: 20px 0;
    }
  }
}

// 新增隐藏头部样式
.header-hidden {
  transform: translateY(-100%);
  opacity: 0;
}

</style>